package com.example.studentproj.service;


import com.example.studentproj.model.Student;
import com.example.studentproj.repository.StudentRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Optional;

@Service
public class StudentServiceLmpl implements StudentService{
    @Autowired
    private StudentRepository studentRepository;

    //实现查找所有数据方法
    @Override
    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    //实现存储接口方法
    @Override
    public void saveStudent(Student student) {
        this.studentRepository.save(student);

    }

    //通过name来查询数据
    @Override
    public List<Student> findByNameContaining(String name) {
        List<Student> optional = studentRepository.findByName(name);

        return optional;
    }

    @Override
    public List<Student> findByClassName(String name) {
        List<Student> optiona2 = studentRepository.findByClassName(name);

        return optiona2;
    }


    @Override
    public Student getStudentByid(Long id) {
        Optional<Student> optional = studentRepository.findById(id);
        Student student = null;
        if( optional.isPresent()){
            student = optional.get();
        }else{
            throw new RuntimeException(" 查无此人，请重输入, id :  "+ id);
        }
        return student;
    }


    @Override
    public void deleteStudentByid(Long id) {
        this.studentRepository.deleteById(id);

    }

    @Override
    public Page<Student> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        //设置排序参数，升序ASC/降序DESC？
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();

        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        return this.studentRepository.findAll(pageable);
    }




}
